package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.*;
import com.okq.service.*;
import com.okq.util.BaseTool;
import com.okq.util.TimeTool;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 产品追溯action
 * 作者 : zdl
 * 日期 : 2017/6/30 10:33
 */
public class TraceAction extends BaseActionSupport {

    private static final long serialVersionUID = -6590744493855263688L;
    /**
     * 产品接口
     */
    @Autowired
    private IProductService productServiceImpl;
    /**
     * 数据字典接口
     */
    @Autowired
    private IDictService dictServiceImpl;
    /**
     * 审批接口
     */
    @Autowired
    private IApprovalService approvalServiceImpl;
    /**
     * 用户接口
     */
    @Autowired
    private IUserService userServiceImpl;
    /**
     * 订单产品接口
     */
    @Autowired
    private IOrderProductService orderProductServiceImpl;
    /**
     * 订单接口
     */
    @Autowired
    private IOrderService orderServiceImpl;
    /**
     * 客户接口
     */
    @Autowired
    private ICustomerService customerServiceImpl;
    /**
     * 物流单接口
     */
    @Autowired
    private ILogisticsSheetService logisticsSheetServiceImpl;
    /**
     * 物流接口
     */
    @Autowired
    private ILogisticsService logisticsServiceImpl;
    /**
     * 工单产品接口
     */
    @Autowired
    private IJobProductService jobProduceServiceImpl;
    /**
     * 工单产品处理接口
     */
    @Autowired
    private IJobProductHistoryService jobProductHistoryServiceImpl;

    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(TraceAction.class);

    private String productCode;//产品编号

    private List<String> productionList;//生产信息
    private String storageInfo;//入库信息
    private String outStoreInfo;//出库信息
    private String logisticsInfo;//物流信息
    private List<String> repairList;//维修信息集合
    private String errorInfo;//错误信息

    /**
     * 根据产品编号追溯产品信息
     *
     * @return 详细信息
     */
    public String search() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            if (StringUtils.isNotBlank(productCode)) {
                Product product = productServiceImpl.getProductByCode(productCode);
                if (product != null) {
                    //获取生产信息
                    findProductionList(product);
                    //获取入库信息
                    findStorageInfo(product);
                    //获取出库信息
                    findOutStoreInfo();
                    //获取物流信息
                    findLogisticsInfo();
                    //获取维修信息
                    findRepairList(product);
                } else {
                    errorInfo = "无法查询到编号为：" + productCode + " 的产品信息，请确认输入正确，重新查询；";
                }
            } else {
                errorInfo = "请输入正确的产品编号";
            }
            Trace trace = new Trace();
            if (productionList != null && !productionList.isEmpty() && productionList.size() > 0) {
                trace.setProductionList(productionList);
            }
            if (StringUtils.isNotBlank(storageInfo)) {
                trace.setStorageInfo(storageInfo);
            }
            if (StringUtils.isNotBlank(outStoreInfo)) {
                trace.setOutStoreInfo(outStoreInfo);
            }
            if (StringUtils.isNotBlank(logisticsInfo)) {
                trace.setLogisticsInfo(logisticsInfo);
            }
            if (repairList != null && !repairList.isEmpty() && repairList.size() > 0) {
                trace.setRepairList(repairList);
            }
            if (StringUtils.isNotBlank(errorInfo)) {
                trace.setErrorInfo(errorInfo);
            }
            String data = BaseTool.toJson(trace);
            out.print(data);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    private void findProductionList(Product product) {
        String productTypeName = dictServiceImpl.getDictByValueAndType(product.getProductType(), "product_type");//产品类型
        String approvalName = "";//审批人姓名
        String approvalTime = "";//审批时间
        Map<String, String> proMap = getApprovalNameAndTime(1, product.getProductionId());
        if (proMap != null && !proMap.isEmpty()) {
            approvalName = proMap.get("approvalName");
            approvalTime = proMap.get("approvalTime");
        }
        productionList.add("编号为：" + productCode + "的" + productTypeName + "设备，于" + approvalTime + "由" + approvalName + "批准开始生产；");
        String weldId = product.getWeldId();
        if (StringUtils.isNotBlank(weldId)) {
            productionList.add(getUserNameById(weldId) + "在" + product.getWeldTime() + "开始焊接；");
        }
        String assembleId = product.getAssembleId();
        if (StringUtils.isNotBlank(assembleId)) {
            productionList.add(getUserNameById(assembleId) + "在" + product.getAssembleTime() + "开始组装；");
        }
        String debugId = product.getDebugId();
        if (StringUtils.isNotBlank(debugId)) {
            productionList.add(getUserNameById(debugId) + "在" + product.getDebugTime() + "开始调试；");
        }
        String checkId = product.getCheckId();
        if (StringUtils.isNotBlank(checkId)) {
            String result = "";
            Integer checkResult = product.getCheckResult();
            if (checkResult == 1) {
                result = "合格";
            } else if (checkResult == 2) {
                result = "不合格";
            }
            productionList.add(getUserNameById(checkId) + "在" + product.getCheckTime() + "开始质检，质检结果为：" + result + "；");
        }
    }

    private void findStorageInfo(Product product) {
        Integer stockState = product.getStockState();
        if (stockState != null) {
            String storageApprovalName = "";
            String storageApprovalTime = "";
            Map<String, String> storageMap = getApprovalNameAndTime(2, product.getProductionId());
            if (storageMap != null && !storageMap.isEmpty()) {
                storageApprovalName = storageMap.get("approvalName");
                storageApprovalTime = storageMap.get("approvalTime");
            }
            storageInfo = "于" + storageApprovalTime + "由" + storageApprovalName + "批准入库；";
        }
    }

    private void findOutStoreInfo() {
        OrderProduct op = orderProductServiceImpl.getOrderProductByCode(productCode);
        if (op != null) {
            String applyName = "";//申请人姓名
            String applyTime = "";//申请时间
            String approvalName = "";//审批人
            String approvalTime = "";//审批时间
            Approval approval = approvalServiceImpl.getApprovalByTypeAndId(3, op.getId());
            if (approval != null) {
                applyName = StringUtils.defaultString(approval.getApplyName(), "");
                applyTime = StringUtils.defaultString(approval.getApplyTime(), "");
                approvalName = StringUtils.defaultString(approval.getApprovalName(), "");
                approvalTime = StringUtils.defaultString(approval.getApprovalTime(), "");
            }
            Order order = orderServiceImpl.getOrderById(op.getOderId());
            String chargeName = "";//销售人
            String customerName = "";//客户名称
            String customerAddress = "";//客户地址
            if (order != null) {
                String chargeId = order.getChargeId();
                if (StringUtils.isNotBlank(chargeId)) {
                    chargeName = getUserNameById(chargeId);
                }
                Customer customer = customerServiceImpl.getCustomerById(order.getCustomerId());
                if (customer != null) {
                    customerName = StringUtils.defaultString(customer.getName(), "");
                    customerAddress = StringUtils.defaultString(customer.getAddress(), "");
                }
            }
            outStoreInfo = "于" + applyTime + "由" + applyName + "申请，并由" + approvalName + "在" + approvalTime
                    + "批准出库，由" + chargeName + "负责销售给" + customerAddress + "的客户" + customerName;
        }
    }

    private void findLogisticsInfo() {
        LogisticsSheet ls = logisticsSheetServiceImpl.getLogisticsSheetByCode(productCode);
        if (ls != null) {
            Integer state = ls.getState();
            if (state > 0) {
                String lname = "";//物流名称
                String logisticsId = ls.getLogisId();
                Logistics l = logisticsServiceImpl.getLogisticsById(logisticsId);
                if (l != null) {
                    Integer logisName = l.getLogisName();
                    lname = dictServiceImpl.getDictByValueAndType(logisName, "logistics_name");
                }
                String logisNum = StringUtils.defaultString(ls.getLogisNum(), "");//单号
                String deliverId = ls.getDeliverId();
                String deliverName = "";//发货人
                if (StringUtils.isNotBlank(deliverId)) {
                    deliverName = getUserNameById(deliverId);
                }
                String deliverTime = StringUtils.defaultString(ls.getDeliverTime(), "");//发货时间
                String signName = StringUtils.defaultString(ls.getSignName(), "");//签收人
                String signTime = StringUtils.defaultString(ls.getSignTime(), "");//签收时间
                String beforeInfo = "于" + deliverTime + "由" + deliverName + "通过" + lname + "物流发货，单号为：" + logisNum + "。";
                String afterInfo = "并与" + signTime + "由客户：" + signName + "签收；";
                if (state == 1 || state == 2) {
                    logisticsInfo = beforeInfo;
                } else {
                    logisticsInfo = beforeInfo + afterInfo;
                }
            }
        }
    }

    private void findRepairList(Product product) {
        String productId = product.getId();
        List<JobProduct> jpList = jobProduceServiceImpl.listJobProductByPid(productId);
        if (jpList != null && !jpList.isEmpty() && jpList.size() > 0) {
            for (JobProduct jp : jpList) {
                List<JobProductHistory> jphList = jobProductHistoryServiceImpl.listJobProductHistoryByJpId(jp.getId());
                if (jphList != null && !jphList.isEmpty() && jphList.size() > 0) {
                    for (JobProductHistory jph : jphList) {
                        String dealTime = TimeTool.timestampToString(jph.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                        String dealName = StringUtils.defaultString(jph.getDealName(), "");
                        String dealInfo = StringUtils.defaultString(jph.getDealInfo(), "");
                        repairList.add("于" + dealTime + "由" + dealName + "处理，处理信息：" + dealInfo);
                    }
                }
            }
        }
    }

    /**
     * 根据审批类型和其他Id(订单产品Id或生产Id)
     *
     * @param type    审批类型 1：生产 2：入库 3：出库 4：质检
     * @param otherId 订单产品Id或生产Id
     * @return map
     */
    private Map<String, String> getApprovalNameAndTime(Integer type, String otherId) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(otherId)) {
            Approval approval = approvalServiceImpl.getApprovalByTypeAndId(type, otherId);
            if (approval != null) {
                String approvalName = StringUtils.defaultString(approval.getApprovalName(), "");
                String approvalTime = StringUtils.defaultString(approval.getApprovalTime(), "");
                map.put("approvalName", approvalName);
                map.put("approvalTime", approvalTime);
            }
        }
        return map;
    }

    private String getUserNameById(String userId) {
        if (StringUtils.isNotBlank(userId)) {
            User user = userServiceImpl.getUserById(userId);
            if (user != null) {
                return StringUtils.defaultString(user.getUserName(), "");
            }
        }
        return "";
    }

    public String getProductCode() {
        return productCode;
    }

    public void setProductCode(String productCode) {
        this.productCode = productCode;
    }

    public List<String> getProductionList() {
        return productionList;
    }

    public void setProductionList(List<String> productionList) {
        this.productionList = productionList;
    }

    public String getStorageInfo() {
        return storageInfo;
    }

    public void setStorageInfo(String storageInfo) {
        this.storageInfo = storageInfo;
    }

    public String getOutStoreInfo() {
        return outStoreInfo;
    }

    public void setOutStoreInfo(String outStoreInfo) {
        this.outStoreInfo = outStoreInfo;
    }

    public String getLogisticsInfo() {
        return logisticsInfo;
    }

    public void setLogisticsInfo(String logisticsInfo) {
        this.logisticsInfo = logisticsInfo;
    }

    public List<String> getRepairList() {
        return repairList;
    }

    public void setRepairList(List<String> repairList) {
        this.repairList = repairList;
    }

    public String getErrorInfo() {
        return errorInfo;
    }

    public void setErrorInfo(String errorInfo) {
        this.errorInfo = errorInfo;
    }
}
